using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using System.Net.Sockets;
using System.IO;
namespace ConfigManager
{
    public class WorkerRole : RoleEntryPoint
    {
        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.WriteLine("$projectname$ entry point called", "Information");
            try 
            {
                TcpListener listener = new TcpListener(
                RoleEnvironment.CurrentRoleInstance.
                InstanceEndpoints["Endpoint1"].IPEndpoint);
                listener.ExclusiveAddressUse = false;
                listener.Start();
                Trace.WriteLine("Listening", RoleEnvironment.CurrentRoleInstance.
                InstanceEndpoints["Endpoint1"].IPEndpoint.Address.ToString());
                ConfigController configController = ConfigController.Instance;
                while (true)
                {
                    Thread.Sleep(1000);
                    if (listener.Pending())
                    {
                        Trace.WriteLine("Incoming Request", "Information");
                        TcpClient c = listener.AcceptTcpClient();
                        Stream s = c.GetStream();
                        StreamReader sr = new StreamReader(s);
                        string text = sr.ReadLine();

                        if (text != null && text.Length > 0)
                        {
                            if (string.Compare("ChangeConfig", text, true) == 0)
                            {
                                string xmlCfgContent = "Can get content from test conclient";
                                configController.SaveConfigration(xmlCfgContent, ConfigType.SPIDER_CONFIG);
                            }
                        }
                    }
                    Trace.WriteLine("Working", "Information");
                }
            
            }
            catch (Exception x)
            {
                Trace.WriteLine(x.Message, "Exception");

            }
        }

        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
           


            return base.OnStart();
        }
    }
}
